package com.example.mystoryapp2.ui.base

import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

/**
 * the basic recycle view adapter
 * make the recycle view simply used
 */
abstract class BaseListAdapter<T, VH : BaseViewHolder>(private val list: ArrayList<T>) :
    RecyclerView.Adapter<VH>() {

    private val TAG = "StoryListAdapter"
    private var mListener: IClickListener<T> = object:IClickListener<T>{
        override fun onClick(view: View, item: T) {
            // nothing to do
        }
    }
    private lateinit var mView: View

    abstract fun getLayoutId(): Int
    abstract fun createViewHolder(itemView: View): VH
    abstract fun onBaseBindViewHolder(holder: VH, position: Int)


    fun setClickListener(listener: IClickListener<T>) {
        mListener = listener
    }

    private fun initClickListener(views:List<View>, item: T) {
        for (view in views) {
            if (mListener != null) {
                view.setOnClickListener {
                    mListener.onClick(it, item)
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setList(list: ArrayList<T>) {
        this.list.clear()
        this.list.addAll(list)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        mView = LayoutInflater.from(parent.context)
            .inflate(getLayoutId(), parent, false)
        Log.d(TAG, "onCreateViewHolder: " + list.size)
        return createViewHolder(mView)
    }

    override fun getItemCount(): Int {
        Log.d(TAG, "getItemCount: " + list.size)
        return list.size
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        onBaseBindViewHolder(holder, position)
        initClickListener(holder.getViewList(), list[position])
    }

    interface IClickListener<T> {
        fun onClick(view: View, item: T)
    }
}